package com.chinatelecom.ifree.business.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SsoUtil {
	private static Logger logger = LoggerFactory.getLogger(SsoUtil.class);

	/**
	 * 获取整个的url访问串
	 * 
	 * @param request
	 */
	public static String getFullUrl(HttpServletRequest request) {
		String url = request.getRequestURL().toString();
		String queryUrl = request.getQueryString() == null ? "" : request.getQueryString();
		String tmp = url + (queryUrl.equals("") ? "" : "?" + queryUrl);
		return convertStr(tmp);
	}

	/**
	 * 转义url 首先转义xml关键字 然后转义url
	 * 
	 * @param str
	 */
	public static String convertStr(String str) {
		String tmp = str.replaceAll("&", "&amp;").replaceAll("<", "&lt;");
		try {
			return URLEncoder.encode(tmp, "utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("", e);
			return "http://localhost:8080/web";
		}
	}

	public static String getUamURL(HttpServletRequest request) {
		StringBuffer CAP01002_URL = new StringBuffer("http://uam.bj.ct10000.com");
		CAP01002_URL.append("/LoginAuth?SSORequestXML=<?xml version=\"1.0\" encoding=\"UTF-8\"?><CAPRoot><SessionHeader><ServiceCode>CAP01002</ServiceCode><Version>2009062411025800</Version><ActionCode>0</ActionCode>");
		CAP01002_URL.append("<TransactionID>");
		CAP01002_URL.append("01001" + DateOper.date2Str(new Date(), "yyyyMMdd") + RandomStringUtils.randomNumeric(10));
		CAP01002_URL.append("</TransactionID><SrcSysID>");
		CAP01002_URL.append("01001");
		CAP01002_URL.append("</SrcSysID><DstSysID>");
		CAP01002_URL.append("01");
		CAP01002_URL.append("</DstSysID><ReqTime>");
		CAP01002_URL.append(DateOper.date2Str(new Date(), "yyyyMMddHHmmss"));
		CAP01002_URL.append("</ReqTime><DigitalSign/></SessionHeader><SessionBody><CT10000SSOAuthReq>");
		CAP01002_URL.append("<RedirectURL>");
		CAP01002_URL.append(SsoUtil.getFullUrl(request));
		CAP01002_URL.append("</RedirectURL></CT10000SSOAuthReq></SessionBody></CAPRoot>");
		logger.info("first request uam:\r\n" + CAP01002_URL.toString());
		return CAP01002_URL.toString();
	}
}
